<?php

namespace App\Http\Controllers\Frontend\Users;

use App\Http\Models\member\MembersFrom;
use App\Http\Controllers\Frontend\ApiController;

class AuthController extends ApiController {

    private $memberService;

    public function __construct() {
        $this->memberService = app('MemberService');
    }

    /**
     * 登录
     *
     */
    public function login(MembersFrom $membersFrom) {
        //bcrypt('admin')
        $userData = $this->memberService->signIn($membersFrom);
        if (!$userData) {
            return $this->errors(EMPTY_DATA, LOGIN_ERROR, 401);
        }
        return $this->success($userData, LOGIN_SUCCESS);
    }

    /**
     * 用户详情
     *
     */
    public function userInfo() {
        $userData = $this->memberService->userInfo();
        return $this->success($userData);
    }

    /**
     * 退出登录
     *
     */
    public function logout() {
        $userData = $this->memberService->logOut();
        return $this->success($userData);
    }

    /**
     * Refresh a token.
     * 刷新token，如果开启黑名单，以前的token便会失效。
     * 值得注意的是用上面的getToken再获取一次Token并不算做刷新，两次获得的Token是并行的，即两个都可用。
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function refresh() {
        $userDataObject = $this->memberService->respondWithToken(auth('api')->refresh());
        if ($userDataObject) {
            $userData = [
                'accessToken' => $userDataObject->original['access_token'],
                'tokenType' => $userDataObject->original['token_type'],
                'expiresIn' => $userDataObject->original['expires_in']
            ];
            return $this->success($userData, REFRECH_SUCCESS);
        }
        return $this->errors(EMPTY_DATA, AUTHENTICATION_ERROR);
    }

}
